package com.cspg.ssss.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cspg.ssss.domain.*;
import com.cspg.ssss.repository.SafeDeptMapMapper;
import com.cspg.ssss.repository.SecurityRiskMapper;
import com.cspg.ssss.service.*;
import com.cspg.ssss.vo.*;
import com.cspg.ssss.vo.convert.CompanyRectifyViewVoConvert;
import com.cspg.ssss.vo.convert.DeptRectifyViewVoConvert;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 问题整改跟踪后台接口
 *
 * @author xiongzq
 * @since 2020-10-20
 */
@RestController
@RequestMapping("/rectify")
public class RectifyController {

    private static Logger log = LoggerFactory.getLogger(RectifyController.class.getName());

    @Autowired
    WxDepartmentService wxDepartmentService;

    @Autowired
    RectifyService rectifyService;

    @Autowired
    SafeDeptMapMapper safeDeptMapMapper;

    @Autowired
    CheckItemService checkItemService;

    @Autowired
    WxSendMsgService wxSendMsgService;
    @Autowired
    DaiBanService daiBanService;
    @Autowired
    SecurityRiskMapper riskMapper;
    @Autowired
    DwdggbmjdDataService dwdggbmjdDataService;

    @Autowired
    GsdgdwjdDataService gsdgdwjdDataService;

    /**
     * 获取用户所在部门列表（一个用户多个部门情况）
     *
     * @param query userid
     * @return
     */
    @GetMapping("/getUserDeptList")
    public ResultVo getUserDeptList(@RequestParam Map<String, String> query) {
        String userid = query.get("userid");
        HashMap<String, Object> condition = new HashMap<String, Object>();
        condition.put("userid", userid);
        List<UserDetailInfoEntity> ls = wxDepartmentService.getDepartmentUserList(condition);
        List<DepartVo> retls = new ArrayList<DepartVo>();
        if (ls != null && ls.size() > 0) {
            for (int i = 0; i < ls.size(); i++) {
                DepartVo v = new DepartVo();
                v.setDepartment_path(ls.get(i).getDepartment_displaypath());
                v.setId(0);
                retls.add(v);
            }
            return ResultVoUtil.success("success", retls);
        }
        return ResultVoUtil.error("未找到部门!");
    }

    /**
     * 根据单位名称，获取单位下一级部门列表
     *
     * @param query user_dept 传入当前人所在部门全路径
     * @return
     */
    @GetMapping("/getDutyDeptList")
    public ResultVo getDutyDeptList(@RequestParam Map<String, String> query) {

        String pdept = query.get("user_dept");
        String deptCompany = getUserCompany(pdept);
        deptCompany = "超高压输电公司/" + deptCompany;
        HashMap<String, Object> condition = new HashMap<String, Object>();
        condition.put("department_pathname", deptCompany);

        List<DepartmentEntity> departEn = wxDepartmentService.getDepartmentListByCondition(condition);

        if (departEn != null && departEn.size() == 1) {
            HashMap<String, Object> subcondition = new HashMap<String, Object>();
            subcondition.put("pid", departEn.get(0).getId());
            List<DepartmentEntity> ls = wxDepartmentService.getDepartmentListByCondition(subcondition);
            List<DepartVo> retls = new ArrayList<DepartVo>();
            if (ls != null && ls.size() > 0) {
                for (int i = 0; i < ls.size(); i++) {
                    DepartVo v = new DepartVo();
                    v.setDepartment_path(ls.get(i).getDepartment_pathname());
                    v.setId(ls.get(i).getId());
                    retls.add(v);
                }
                return ResultVoUtil.success("success", retls);
            }
        }

        return ResultVoUtil.error("未查到子部门");
    }

    /**
     * 获取公司层面考核问题列表
     *
     * @param req
     * @return
     */
    @PostMapping("/getCompanyRectifyList")
    public ResultVo getCompanyRectifyList(@RequestBody JSONObject req) {
        PageInfoVo<CompanyRectifyViewVo> retPageVo = new PageInfoVo<CompanyRectifyViewVo>();

        String strPgnum = req.getString("pageNum");
        String strPgsize = req.getString("pageSize");
        String user_dept = req.getString("user_dept");
        String op = req.getString("op");
        String strRectifyStatus = req.getString("rectify_status");
        String strProblemType = req.getString("problem_type");

        String carrier = req.getString("carrier");


        Map<String, Object> condition = new HashMap<String, Object>();
        condition.put("problem_type", Integer.parseInt(strProblemType));

        if (strRectifyStatus != null && (strRectifyStatus.equals("") == false)) {
            condition.put("rectify_status", strRectifyStatus);
        }
        String matters = null;
        if (carrier != null && (carrier.equals("") == false)) {
            List<CheckItem> cls = checkItemService.getCheckCategroy();
            for (int k = 0; k < cls.size(); k++) {
                if (cls.get(k).getId().equals(carrier)) {
                    matters = cls.get(k).getItem();//根据考核载体编号找到考核载体内容后，将变量赋值为考核载体字符内容
                    break;
                }
            }

        }

        //根据考核载体编号获取考核载体描述内容
        if (matters != null && !matters.isEmpty()) {
            condition.put("matters", matters);
        }


        if (op.equals("review")) {//安监部门列表
            if (!user_dept.startsWith("超高压输电公司/公司本部/安全监管部")) {
                return ResultVoUtil.error("0401", "非公司本部安监部门人员");
            }
        }

        if (op.equals("duty")) {//责任部门列表
            condition.put("duty_dept", user_dept);
        }

        PageInfo<CompanyRectifyViewEntity> ls = rectifyService.getCompanyRectifyListByCondition(Integer.parseInt(strPgnum), Integer.parseInt(strPgsize), condition);

        List<CompanyRectifyViewVo> retls = CompanyRectifyViewVoConvert.ConvertList(ls.getList());
        for (CompanyRectifyViewVo vo : retls) {
            if (StringUtils.isEmpty(vo.getDuty_dept())) {
                vo.setDutyDept(ConvertDeptToPath(vo.getBmmc()));
            } else {
                vo.setDutyDept(vo.getDuty_dept());
            }
            vo.setReviewDept("超高压输电公司/公司本部/安全监管部（应急指挥中心）");
        }
        retPageVo.setPageNum(ls.getPageNum());
        retPageVo.setPageSize(ls.getPageSize());
        retPageVo.setTotal(ls.getTotal());
        retPageVo.setList(retls);

        return ResultVoUtil.success("success", retPageVo);

    }

    private String getUserCompany(String userdept) {
        String[] arrPath = userdept.split("/");
        if (arrPath == null || arrPath.length < 2) {
            return "";
        }
        if (arrPath.length >= 3 && arrPath[2].equals("海口分局")) {
            return arrPath[1] + "/" + arrPath[2];
        }
        return arrPath[1];
    }

    private String getSafeDeptPath(String userdept) {
        String CompanyPath = getUserCompany(userdept);
        if (!CompanyPath.equals("")) {
            List<SafeDeptMap> ls = safeDeptMapMapper.selectDeptNameForCompany(CompanyPath);
            if (ls != null && ls.size() == 1) {
                return "超高压输电公司/" + ls.get(0).getCompany() + "/" + ls.get(0).getSafe_dept();
            }
        }
        return "";
    }

    /**
     * 将部门路径由/分隔改成->分隔，去掉超高压前缀
     *
     * @param deptPath
     * @return
     */
    private String ConvertToDeptPath(String deptPath) {
        if (deptPath.startsWith("超高压输电公司/") == false) {
            return deptPath;
        }
        return deptPath.substring(8).replaceAll("/", "->");
    }

    /**
     * 将部门路径由->分隔改成/分隔，加上超高压前缀
     *
     * @param deptPath
     * @return
     */
    private String ConvertDeptToPath(String deptPath) {
        String newpath = deptPath.replaceAll("->", "/");
        newpath = "超高压输电公司/" + newpath;
        return newpath;
    }

    /**
     * 获取非公司层面考核问题列表
     *
     * @param req
     * @return
     */
    @PostMapping("/getDeptRectifyList")
    public ResultVo getDeptRectifyList(@RequestBody JSONObject req) {
        PageInfoVo<DeptRectifyViewVo> retPageVo = new PageInfoVo<DeptRectifyViewVo>();

        String strPgnum = req.getString("pageNum");
        String strPgsize = req.getString("pageSize");
        String user_dept = req.getString("user_dept");
        String op = req.getString("op");
        String strRectifyStatus = req.getString("rectify_status");
        String strProblemType = req.getString("problem_type");

        String carrier = req.getString("carrier");

        Map<String, Object> condition = new HashMap<String, Object>();
        condition.put("problem_type", Integer.parseInt(strProblemType));

        if (strRectifyStatus != null && (strRectifyStatus.equals("") == false)) {
            condition.put("rectify_status", strRectifyStatus);
        }

        String matters = null;
        if (carrier != null && (carrier.equals("") == false)) {
            List<CheckItem> cls = checkItemService.getCheckCategroy();
            for (int k = 0; k < cls.size(); k++) {
                if (cls.get(k).getId().equals(carrier)) {
                    matters = cls.get(k).getItem();//根据考核载体编号找到考核载体内容后，将变量赋值为考核载体字符内容
                    break;
                }
            }

        }

        //根据考核载体编号获取考核载体描述内容
        if (matters != null && !matters.isEmpty()) {
            condition.put("matters", matters);
        }

        if (op.equals("review")) {//安监部门列表
            String safeDept = getSafeDeptPath(user_dept);
            if (safeDept.equals("") || (!user_dept.startsWith(safeDept))) {
                return ResultVoUtil.error("0401", "非安监部门人员");
            }
            //查询所以该单位的问题
            String strCompany = getUserCompany(user_dept);
            if (strCompany.endsWith("广州局")) {
                condition.put("ne_bmmc", "广州局->海口分局");
            }
            strCompany = strCompany.replaceAll("/", "->");
            condition.put("bmmc", strCompany);

        }

        if (op.equals("duty")) {//责任部门列表
            condition.put("duty_dept", user_dept);
        }

        if (op.equals("manage")) {//专业管理部门列表
            condition.put("manage_dept", user_dept);
        }

        PageInfo<DeptRectifyViewEntity> ls = rectifyService.getDeptRectifyListByCondition(Integer.parseInt(strPgnum), Integer.parseInt(strPgsize), condition);

        List<DeptRectifyViewVo> retls = DeptRectifyViewVoConvert.ConvertList(ls.getList());
        for (DeptRectifyViewVo vo : retls) {
            if (StringUtils.isEmpty(vo.getDuty_dept())) {
                vo.setDutyDept(ConvertDeptToPath(vo.getBmmc()));
            } else {
                vo.setDutyDept(vo.getDuty_dept());
            }
            vo.setReviewDept(getSafeDeptPath(ConvertDeptToPath(vo.getBmmc())));
        }
        retPageVo.setPageNum(ls.getPageNum());
        retPageVo.setPageSize(ls.getPageSize());
        retPageVo.setTotal(ls.getTotal());
        retPageVo.setList(retls);

        return ResultVoUtil.success("success", retPageVo);

    }

    /**
     * 公司层面考核问题流程流转
     *
     * @param req
     * @return
     */
    @PostMapping("/updateCompanyRectifyProblem")
    public ResultVo updateCompanyRectifyProblem(@RequestBody JSONObject req) {
        String op = req.getString("op");
        String strProblemType = req.getString("problem_type");
        String userid = req.getString("user_id");
        String username = req.getString("user_name");
        String approve_result = req.getString("approve_result");//审核结果 0-同意，1-拒绝
        String approve_content = req.getString("approve_content");//审核意见，文本
        JSONObject jsonObject = req.getJSONObject("rectifyProblem");
        String strDutyDept = bmmcToDeptFullPath(jsonObject.getString("bmmc"));

        JSONArray receivers = req.getJSONArray("receivers");
        StringBuilder userNames = new StringBuilder();
        String deptName = "";
        if (receivers != null && !receivers.isEmpty()) {
            for (int i = 0; i < receivers.size(); i++) {
                userNames.append("、").append(receivers.getJSONObject(i).getString("user_name"));
                deptName = receivers.getJSONObject(i).getString("department_displaypath");
            }
        }

        if (op.equals("duty")) {//指定责任部门
            String problemid = jsonObject.getString("problem_id");
            if (problemid == null || problemid.equals("")) {
                Map<String, Object> insertCondition = new HashMap<String, Object>();
                insertCondition.put("problem_id", jsonObject.getString("id"));

                insertCondition.put("duty_dept", strDutyDept);
                insertCondition.put("duty_date", new Date());
                insertCondition.put("rectify_status", "duty");
                insertCondition.put("problem_type", Integer.parseInt(strProblemType));

                rectifyService.insertCompanyRectify(insertCondition);

            } else {
                Map<String, Object> updateCondition = new HashMap<String, Object>();
                updateCondition.put("problem_id", jsonObject.getString("id"));

                updateCondition.put("duty_dept", strDutyDept);
                updateCondition.put("duty_date", new Date());
                updateCondition.put("rectify_status", "duty");
                rectifyService.updateCompanyRectify(updateCondition);

            }

            RectifyHistoryEntity historyEntity = new RectifyHistoryEntity();
            historyEntity.setProblem_id(jsonObject.getString("id"));
            historyEntity.setOp_content("指定责任部门：" + strDutyDept);
            historyEntity.setOp_datetime(new Date());
            historyEntity.setOp_event("duty");
            historyEntity.setOp_userid(userid);
            historyEntity.setOp_username(username);
            historyEntity.setNext_username(deptName.replace("超高压输电公司/", "") + "[" + userNames.substring(1) + "]");
            rectifyService.insertRectifyHistory(historyEntity);
        }

        if (op.equals("reject_duty")) {//指定责任部门回退，回退到unprocess

            Map<String, Object> updateCondition = new HashMap<String, Object>();
            updateCondition.put("problem_id", jsonObject.getString("id"));
            updateCondition.put("duty_dept", "");
            updateCondition.put("rectify_status", "unprocess");
            rectifyService.updateCompanyRectify(updateCondition);

            RectifyHistoryEntity historyEntity = new RectifyHistoryEntity();
            historyEntity.setProblem_id(jsonObject.getString("id"));
            historyEntity.setOp_content("责任部门退回");
            historyEntity.setOp_datetime(new Date());
            historyEntity.setOp_event("reject_duty");
            historyEntity.setOp_userid(userid);
            historyEntity.setOp_username(username);
            historyEntity.setNext_username("公司本部/安全监管部（应急指挥中心）");
            rectifyService.insertRectifyHistory(historyEntity);

        }

        if (op.equals("rectify")) {//制定整改措施提交

            try {
                Map<String, Object> updateCondition = new HashMap<String, Object>();
                updateCondition.put("problem_id", jsonObject.getString("id"));
                updateCondition.put("rectify_content", jsonObject.getString("rectify_content"));
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                Date deadline = sdf.parse(jsonObject.getString("rectify_deadline"));
                updateCondition.put("rectify_deadline", deadline);
                updateCondition.put("rectify_status", "rectify");
                rectifyService.updateCompanyRectify(updateCondition);

                RectifyHistoryEntity historyEntity = new RectifyHistoryEntity();
                historyEntity.setProblem_id(jsonObject.getString("id"));
                historyEntity.setOp_content("制定整改措施：" + jsonObject.getString("rectify_content") + "\r\n" + "整改期限" + jsonObject.getString("rectify_deadline"));
                historyEntity.setOp_datetime(new Date());
                historyEntity.setOp_event("rectify");
                historyEntity.setOp_userid(userid);
                historyEntity.setOp_username(username);
                historyEntity.setNext_username(deptName.replace("超高压输电公司/", "") + "[" + userNames.substring(1) + "]");
                rectifyService.insertRectifyHistory(historyEntity);
            } catch (ParseException e) {
                e.printStackTrace();
            }

        }

        if (op.equals("approve")) {//提交审核

            if (approve_result.equals("1")) {
                Map<String, Object> updateCondition = new HashMap<String, Object>();
                updateCondition.put("problem_id", jsonObject.getString("id"));
                updateCondition.put("rectify_status", "duty");
                rectifyService.updateCompanyRectify(updateCondition);

                RectifyHistoryEntity historyEntity = new RectifyHistoryEntity();
                historyEntity.setProblem_id(jsonObject.getString("id"));
                historyEntity.setOp_content("整改措施审核不通过：" + approve_content);
                historyEntity.setOp_datetime(new Date());
                historyEntity.setOp_event("approve");
                historyEntity.setOp_userid(userid);
                historyEntity.setOp_username(username);
                historyEntity.setNext_username(strDutyDept.replace("超高压输电公司/", ""));
                rectifyService.insertRectifyHistory(historyEntity);
            }

            if (approve_result.equals("0")) {
                Map<String, Object> updateCondition = new HashMap<String, Object>();
                updateCondition.put("problem_id", jsonObject.getString("id"));
                updateCondition.put("rectify_status", "approve");
                rectifyService.updateCompanyRectify(updateCondition);

                RectifyHistoryEntity historyEntity = new RectifyHistoryEntity();
                historyEntity.setProblem_id(jsonObject.getString("id"));
                historyEntity.setOp_content("整改措施审核通过：" + approve_content);
                historyEntity.setOp_datetime(new Date());
                historyEntity.setOp_event("approve");
                historyEntity.setOp_userid(userid);
                historyEntity.setOp_username(username);
                historyEntity.setNext_username(deptName.replace("超高压输电公司/", "") + "[" + userNames.substring(1) + "]");
                rectifyService.insertRectifyHistory(historyEntity);
            }

        }

        if (op.equals("commit")) {//落实整改

            Map<String, Object> updateCondition = new HashMap<String, Object>();
            updateCondition.put("problem_id", jsonObject.getString("id"));
            updateCondition.put("rectify_commit", jsonObject.getString("rectify_commit"));
            updateCondition.put("rectify_commit_date", new Date());
            updateCondition.put("rectify_status", "commit");
            rectifyService.updateCompanyRectify(updateCondition);

            RectifyHistoryEntity historyEntity = new RectifyHistoryEntity();
            historyEntity.setProblem_id(jsonObject.getString("id"));
            historyEntity.setOp_content("提交整改验收，整改情况：" + jsonObject.getString("rectify_commit"));
            historyEntity.setOp_datetime(new Date());
            historyEntity.setOp_event("commit");
            historyEntity.setOp_userid(userid);
            historyEntity.setOp_username(username);
            historyEntity.setNext_username(deptName.replace("超高压输电公司/", "") + "[" + userNames.substring(1) + "]");
            rectifyService.insertRectifyHistory(historyEntity);
        }

        if (op.equals("complete")) {//验收
            if (approve_result.equals("1")) {
                Map<String, Object> updateCondition = new HashMap<String, Object>();
                updateCondition.put("problem_id", jsonObject.getString("id"));
                updateCondition.put("rectify_status", "approve");
                rectifyService.updateCompanyRectify(updateCondition);

                RectifyHistoryEntity historyEntity = new RectifyHistoryEntity();
                historyEntity.setProblem_id(jsonObject.getString("id"));
                historyEntity.setOp_content("整改验收不通过：" + approve_content);
                historyEntity.setOp_datetime(new Date());
                historyEntity.setOp_event("complete");
                historyEntity.setOp_userid(userid);
                historyEntity.setOp_username(username);
                historyEntity.setNext_username(strDutyDept.replace("超高压输电公司/", ""));
                rectifyService.insertRectifyHistory(historyEntity);
            }

            if (approve_result.equals("0")) {
                Map<String, Object> updateCondition = new HashMap<String, Object>();
                updateCondition.put("problem_id", jsonObject.getString("id"));
                updateCondition.put("rectify_status", "complete");
                updateCondition.put("complete_date", new Date());
                rectifyService.updateCompanyRectify(updateCondition);

                RectifyHistoryEntity historyEntity = new RectifyHistoryEntity();
                historyEntity.setProblem_id(jsonObject.getString("id"));
                historyEntity.setOp_content("整改验收通过：" + approve_content);
                historyEntity.setOp_datetime(new Date());
                historyEntity.setOp_event("complete");
                historyEntity.setOp_userid(userid);
                historyEntity.setOp_username(username);
                rectifyService.insertRectifyHistory(historyEntity);
            }
        }

        //发送消息
        sendImMessage(op, req, jsonObject, 0);
        return ResultVoUtil.success("success", null);
    }

    /**
     * 非公司层面考核问题流转
     */
    @PostMapping("/updateDeptRectifyProblem")
    public ResultVo updateDeptRectifyProblem(@RequestBody JSONObject req) {

        String op = req.getString("op");
        String strProblemType = req.getString("problem_type");
        String userid = req.getString("user_id");
        String username = req.getString("user_name");
        String user_dept = req.getString("user_dept");
        String approve_result = req.getString("approve_result");//审核结果 0-同意，1-拒绝
        String approve_content = req.getString("approve_content");//审核意见，文本
        JSONObject jsonObject = req.getJSONObject("rectifyProblem");

        JSONArray receivers = req.getJSONArray("receivers");
        StringBuilder userNames = new StringBuilder();
        String deptName = "";
        if (receivers != null && !receivers.isEmpty()) {
            for (int i = 0; i < receivers.size(); i++) {
                userNames.append("、").append(receivers.getJSONObject(i).getString("user_name"));
                deptName = receivers.getJSONObject(i).getString("department_displaypath");
            }
        }
        String strDutyDept = bmmcToDeptFullPath(jsonObject.getString("bmmc"));
        if (op.equals("duty")) {//指定责任部门
            String problemid = jsonObject.getString("problem_id");
            if (problemid == null || problemid.equals("")) {
                Map<String, Object> insertCondition = new HashMap<String, Object>();
                insertCondition.put("problem_id", jsonObject.getString("id"));

                insertCondition.put("duty_dept", strDutyDept);
                insertCondition.put("duty_date", new Date());
                insertCondition.put("rectify_status", "duty");
                insertCondition.put("problem_type", Integer.parseInt(strProblemType));
                insertCondition.put("review_dept", getSafeDeptPath(user_dept));
                rectifyService.insertDeptRectify(insertCondition);

            } else {
                Map<String, Object> updateCondition = new HashMap<String, Object>();
                updateCondition.put("problem_id", jsonObject.getString("id"));
                updateCondition.put("duty_dept", strDutyDept);
                updateCondition.put("duty_date", new Date());
                updateCondition.put("rectify_status", "duty");
                rectifyService.updateDeptRectify(updateCondition);
            }

            RectifyHistoryEntity historyEntity = new RectifyHistoryEntity();
            historyEntity.setProblem_id(jsonObject.getString("id"));
            historyEntity.setOp_content("指定责任部门：" + strDutyDept);
            historyEntity.setOp_datetime(new Date());
            historyEntity.setOp_event("duty");
            historyEntity.setOp_userid(userid);
            historyEntity.setOp_username(username);
            historyEntity.setNext_username(deptName.replace("超高压输电公司/", "") + "[" + userNames.substring(1) + "]");
            rectifyService.insertRectifyHistory(historyEntity);
        }

        if (op.equals("reject_duty")) {//指定责任部门回退，回退到unprocess

            Map<String, Object> updateCondition = new HashMap<String, Object>();
            updateCondition.put("problem_id", jsonObject.getString("id"));
            updateCondition.put("duty_dept", "");
            updateCondition.put("rectify_status", "unprocess");
            rectifyService.updateDeptRectify(updateCondition);

            RectifyHistoryEntity historyEntity = new RectifyHistoryEntity();
            historyEntity.setProblem_id(jsonObject.getString("id"));
            historyEntity.setOp_content("责任部门退回");
            historyEntity.setOp_datetime(new Date());
            historyEntity.setOp_event("reject_duty");
            historyEntity.setOp_userid(userid);
            historyEntity.setOp_username(username);
            historyEntity.setNext_username(getSafeDeptPath(strDutyDept).replace("超高压输电公司/", ""));
            rectifyService.insertRectifyHistory(historyEntity);

        }

        if (op.equals("rectify")) {//制定整改措施提交
            int ftype = jsonObject.getIntValue("flow_type");

            try {
                Map<String, Object> updateCondition = new HashMap<String, Object>();
                updateCondition.put("problem_id", jsonObject.getString("id"));
                updateCondition.put("rectify_content", jsonObject.getString("rectify_content"));
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                Date deadline = sdf.parse(jsonObject.getString("rectify_deadline"));
                updateCondition.put("rectify_deadline", deadline);

                updateCondition.put("flow_type", ftype);
                updateCondition.put("rectify_status", "rectify");
                if (ftype == 0) {//一级审核

                }
                if (ftype == 1) {//二级审核
                    updateCondition.put("manage_dept", jsonObject.getString("manage_dept"));
                }

                rectifyService.updateDeptRectify(updateCondition);

                RectifyHistoryEntity historyEntity = new RectifyHistoryEntity();
                historyEntity.setProblem_id(jsonObject.getString("id"));
                String content = "制定整改措施：" + jsonObject.getString("rectify_content") + "\r\n" + "整改期限" + jsonObject.getString("rectify_deadline");
                if (ftype == 1) {
                    content += ",流程采用二级审核，专业管理部门选择：" + jsonObject.getString("manage_dept");
                }
                if (ftype == 0) {
                    content += ",流程采用一级审核";
                }
                historyEntity.setOp_content(content);
                historyEntity.setOp_datetime(new Date());
                historyEntity.setOp_event("rectify");
                historyEntity.setOp_userid(userid);
                historyEntity.setOp_username(username);
                historyEntity.setNext_username(deptName.replace("超高压输电公司/", "") + "[" + userNames.substring(1) + "]");
                rectifyService.insertRectifyHistory(historyEntity);
            } catch (ParseException e) {
                e.printStackTrace();
            }

        }

        if (op.equals("approve")) {
            String status = jsonObject.getString("rectify_status");
            int ftype = jsonObject.getIntValue("flow_type");
            if (status.equals("rectify") && ftype == 1) {
                op = "manage_approve";
            }
            if (status.equals("manage_approve") || (status.equals("rectify") && ftype == 0)) {
                op = "review_approve";
            }
        }

        if (op.equals("manage_approve")) {
            if (approve_result.equals("1")) {
                Map<String, Object> updateCondition = new HashMap<String, Object>();
                updateCondition.put("problem_id", jsonObject.getString("id"));
                updateCondition.put("rectify_status", "duty");
                rectifyService.updateDeptRectify(updateCondition);

                RectifyHistoryEntity historyEntity = new RectifyHistoryEntity();
                historyEntity.setProblem_id(jsonObject.getString("id"));
                historyEntity.setOp_content("整改措施专业管理部门审核不通过：" + approve_content);
                historyEntity.setOp_datetime(new Date());
                historyEntity.setOp_event("manage_approve");
                historyEntity.setOp_userid(userid);
                historyEntity.setOp_username(username);
                historyEntity.setNext_username(strDutyDept.replace("超高压输电公司/", ""));
                rectifyService.insertRectifyHistory(historyEntity);
            }

            if (approve_result.equals("0")) {
                Map<String, Object> updateCondition = new HashMap<String, Object>();
                updateCondition.put("problem_id", jsonObject.getString("id"));
                updateCondition.put("rectify_status", "manage_approve");
                rectifyService.updateDeptRectify(updateCondition);

                RectifyHistoryEntity historyEntity = new RectifyHistoryEntity();
                historyEntity.setProblem_id(jsonObject.getString("id"));
                historyEntity.setOp_content("整改措施专业管理部门审核通过：" + approve_content);
                historyEntity.setOp_datetime(new Date());
                historyEntity.setOp_event("manage_approve");
                historyEntity.setOp_userid(userid);
                historyEntity.setOp_username(username);
                historyEntity.setNext_username(deptName.replace("超高压输电公司/", "") + "[" + userNames.substring(1) + "]");
                rectifyService.insertRectifyHistory(historyEntity);
            }
        }

        if (op.equals("review_approve")) {
            if (approve_result.equals("1")) {
                Map<String, Object> updateCondition = new HashMap<String, Object>();
                updateCondition.put("problem_id", jsonObject.getString("id"));
                updateCondition.put("rectify_status", "duty");
                rectifyService.updateDeptRectify(updateCondition);

                RectifyHistoryEntity historyEntity = new RectifyHistoryEntity();
                historyEntity.setProblem_id(jsonObject.getString("id"));
                historyEntity.setOp_content("整改措施安监部门审核不通过：" + approve_content);
                historyEntity.setOp_datetime(new Date());
                historyEntity.setOp_event("approve");
                historyEntity.setOp_userid(userid);
                historyEntity.setOp_username(username);
                historyEntity.setNext_username(strDutyDept.replace("超高压输电公司/", ""));
                rectifyService.insertRectifyHistory(historyEntity);
            }

            if (approve_result.equals("0")) {
                Map<String, Object> updateCondition = new HashMap<String, Object>();
                updateCondition.put("problem_id", jsonObject.getString("id"));
                updateCondition.put("rectify_status", "approve");
                rectifyService.updateDeptRectify(updateCondition);

                RectifyHistoryEntity historyEntity = new RectifyHistoryEntity();
                historyEntity.setProblem_id(jsonObject.getString("id"));
                historyEntity.setOp_content("整改措施安监部门审核通过：" + approve_content);
                historyEntity.setOp_datetime(new Date());
                historyEntity.setOp_event("approve");
                historyEntity.setOp_userid(userid);
                historyEntity.setOp_username(username);
                historyEntity.setNext_username(deptName.replace("超高压输电公司/", "") + "[" + userNames.substring(1) + "]");
                rectifyService.insertRectifyHistory(historyEntity);
            }
        }

        if (op.equals("commit")) {//落实整改
            Map<String, Object> updateCondition = new HashMap<String, Object>();
            updateCondition.put("problem_id", jsonObject.getString("id"));
            updateCondition.put("rectify_commit", jsonObject.getString("rectify_commit"));
            updateCondition.put("rectify_commit_date", new Date());
            updateCondition.put("rectify_status", "commit");
            rectifyService.updateDeptRectify(updateCondition);

            RectifyHistoryEntity historyEntity = new RectifyHistoryEntity();
            historyEntity.setProblem_id(jsonObject.getString("id"));
            historyEntity.setOp_content("提交整改验收，整改情况：" + jsonObject.getString("rectify_commit"));
            historyEntity.setOp_datetime(new Date());
            historyEntity.setOp_event("commit");
            historyEntity.setOp_userid(userid);
            historyEntity.setOp_username(username);
            historyEntity.setNext_username(deptName.replace("超高压输电公司/", "") + "[" + userNames.substring(1) + "]");
            rectifyService.insertRectifyHistory(historyEntity);
        }

        if (op.equals("complete")) {
            String status = jsonObject.getString("rectify_status");
            int ftype = jsonObject.getIntValue("flow_type");
            if (status.equals("commit") && ftype == 1) {
                op = "manage_complete";
            }
            if (status.equals("manage_complete") || (status.equals("commit") && ftype == 0)) {
                op = "review_complete";
            }
        }

        if (op.equals("manage_complete")) {//验收
            if (approve_result.equals("1")) {
                Map<String, Object> updateCondition = new HashMap<String, Object>();
                updateCondition.put("problem_id", jsonObject.getString("id"));
                updateCondition.put("rectify_status", "approve");

                rectifyService.updateDeptRectify(updateCondition);

                RectifyHistoryEntity historyEntity = new RectifyHistoryEntity();
                historyEntity.setProblem_id(jsonObject.getString("id"));
                historyEntity.setOp_content("整改专业部门验收不通过：" + approve_content);
                historyEntity.setOp_datetime(new Date());
                historyEntity.setOp_event("manage_complete");
                historyEntity.setOp_userid(userid);
                historyEntity.setOp_username(username);
                historyEntity.setNext_username(strDutyDept.replace("超高压输电公司/", ""));
                rectifyService.insertRectifyHistory(historyEntity);
            }

            if (approve_result.equals("0")) {
                Map<String, Object> updateCondition = new HashMap<String, Object>();
                updateCondition.put("problem_id", jsonObject.getString("id"));
                updateCondition.put("rectify_status", "manage_complete");
                updateCondition.put("complete_date", new Date());
                rectifyService.updateDeptRectify(updateCondition);

                RectifyHistoryEntity historyEntity = new RectifyHistoryEntity();
                historyEntity.setProblem_id(jsonObject.getString("id"));
                historyEntity.setOp_content("整改专业管理部门验收通过：" + approve_content);
                historyEntity.setOp_datetime(new Date());
                historyEntity.setOp_event("manage_complete");
                historyEntity.setOp_userid(userid);
                historyEntity.setOp_username(username);
                historyEntity.setNext_username(deptName.replace("超高压输电公司/", "") + "[" + userNames.substring(1) + "]");
                rectifyService.insertRectifyHistory(historyEntity);
            }
        }

        if (op.equals("review_complete")) {//安监部门最终验收
            int ftype = jsonObject.getIntValue("flow_type");
            if (approve_result.equals("1")) {
                Map<String, Object> updateCondition = new HashMap<String, Object>();
                updateCondition.put("problem_id", jsonObject.getString("id"));
                updateCondition.put("rectify_status", "approve");

                rectifyService.updateDeptRectify(updateCondition);

                RectifyHistoryEntity historyEntity = new RectifyHistoryEntity();
                historyEntity.setProblem_id(jsonObject.getString("id"));
                historyEntity.setOp_content("整改最终验收不通过：" + approve_content);
                historyEntity.setOp_datetime(new Date());
                historyEntity.setOp_event("complete");
                historyEntity.setOp_userid(userid);
                historyEntity.setOp_username(username);
                historyEntity.setNext_username(strDutyDept.replace("超高压输电公司/", ""));
                rectifyService.insertRectifyHistory(historyEntity);
            }

            if (approve_result.equals("0")) {
                Map<String, Object> updateCondition = new HashMap<String, Object>();
                updateCondition.put("problem_id", jsonObject.getString("id"));
                updateCondition.put("rectify_status", "complete");
                if (ftype == 0) {
                    updateCondition.put("complete_date", new Date());
                }
                //updateCondition.put("complete_date",new Date());
                rectifyService.updateDeptRectify(updateCondition);

                RectifyHistoryEntity historyEntity = new RectifyHistoryEntity();
                historyEntity.setProblem_id(jsonObject.getString("id"));
                historyEntity.setOp_content("整改最终验收通过：" + approve_content);
                historyEntity.setOp_datetime(new Date());
                historyEntity.setOp_event("complete");
                historyEntity.setOp_userid(userid);
                historyEntity.setOp_username(username);
                rectifyService.insertRectifyHistory(historyEntity);
            }
        }

        //发送消息
        sendImMessage(op, req, jsonObject, 1);
        return ResultVoUtil.success("success", null);
    }

    /**
     * 整改流转过程中发送即时消息提醒
     */
    private void sendImMessage(String op, JSONObject reqObj, JSONObject jsonObject, int check_type) {
        JSONArray receivers = reqObj.getJSONArray("receivers");
        List<String> userList = new ArrayList<>();
        if (receivers != null && !receivers.isEmpty()) {
            for (int i = 0; i < receivers.size(); i++) {
                userList.add(receivers.getJSONObject(i).getString("user_id"));
            }
        }
        BacklogEntity updateBacklog = new BacklogEntity();
        int approve_result = reqObj.getIntValue("approve_result");//审核结果 0-同意，1-拒绝
        String problem_id = jsonObject.getString("id");
        String strDutyDept = bmmcToDeptFullPath(jsonObject.getString("bmmc"));
        if (op.equals("delete")) {
            DwdggbmjdDataEntity dwdggbmjdDataEntity = dwdggbmjdDataService.selectDataId(problem_id);
            boolean con = false;
            if (dwdggbmjdDataEntity != null) {
                dwdggbmjdDataService.delete(problem_id);
                userList.clear();
                userList.add(dwdggbmjdDataEntity.getDrman());
                wxSendMsgService.rectifyDeleteTipInfo(userList, 1, dwdggbmjdDataEntity.getWtms());
                daiBanService.deleteBacklogByProblemId(problem_id);
                con = true;
            } else {
                GsdgdwjdDataEntity entity = gsdgdwjdDataService.selectDataId(problem_id);
                if (entity != null) {
                    gsdgdwjdDataService.delete(problem_id);
                    userList.clear();
                    userList.add(entity.getDrman());
                    wxSendMsgService.rectifyDeleteTipInfo(userList, 0, entity.getWtms());
                    daiBanService.deleteBacklogByProblemId(problem_id);
                    con = true;
                }
            }
            if (con) {
                String id = riskMapper.selectIdByDwmc(jsonObject.getString("dwmc"),jsonObject.getString("createa_time"));
                if (id != null) {
                    SecurityRiskLogEntity logEntity = new SecurityRiskLogEntity();
                    logEntity.setRiskId(id);
                    logEntity.setType(3);
                    logEntity.setWarringReason("删除1条"+jsonObject.getString("wtyzcd"));
                    logEntity.setCreateTime(new Date());
                    logEntity.setCreateBy(reqObj.getString("user_name"));
                    riskMapper.insertLog(logEntity);
                }
            }
        }

        if (op.equals("duty")) {//指定责任部门
            wxSendMsgService.dutyTipInfo(userList, check_type);
            //修改待办状态
            updateBacklog.setDbstatus("1");
            updateBacklog.setBmmc(strDutyDept);
        }
        if (op.equals("reject_duty")) {//指定责任部门回退，回退到unprocess
            //修改待办状态
            updateBacklog.setDbstatus("0");
            updateBacklog.setBmmc(getSafeDeptPath(strDutyDept));
        }
        if (op.equals("rectify")) {//制定整改措施
            if (check_type == 0) {
                wxSendMsgService.rectifyTipInfo(userList, check_type, 0);
                //修改待办状态
                updateBacklog.setDbstatus("2");
                updateBacklog.setBmmc("超高压输电公司/公司本部/安全监管部（应急指挥中心）");
            } else {
                int ftype = jsonObject.getIntValue("flow_type");
                wxSendMsgService.rectifyTipInfo(userList, check_type, ftype);
                if (ftype == 1) {//二级审核
                    //修改待办状态
                    updateBacklog.setDbstatus("5");
                    updateBacklog.setBmmc(jsonObject.getString("manage_dept"));
                } else {//一级审核
                    //修改待办状态
                    updateBacklog.setDbstatus("2");
                    updateBacklog.setBmmc(getSafeDeptPath(strDutyDept));
                }
            }
        }
        if (op.equals("approve")) {//提交审核
            if (check_type == 0) {//一级审核
//                List<CompanyRectifyViewEntity> ls = getCompanyRectify(reqObj, jsonObject);
//                if (ls.size() > 0) {
                if (approve_result == 1) {
                    userList.clear();
                    List<RectifyHistoryEntity> historyList = rectifyService.getRectifyHistory(jsonObject.getString("problem_id"));
                    for (RectifyHistoryEntity entity : historyList) {
                        if (entity.getOp_event().equals("rectify")) {
                            userList.add(entity.getOp_userid());
                            break;
                        }
                    }
                }
                wxSendMsgService.approveTipInfo(userList, approve_result);
                //修改待办状态
                updateBacklog.setDbstatus(approve_result == 1 ? "1" : "3");
                updateBacklog.setBmmc(strDutyDept);
//                updateBacklog.setBmmc(ls.get(0).getDuty_dept());
//                }
            } else { //二级审核
                String status = jsonObject.getString("rectify_status");
                int ftype = jsonObject.getIntValue("flow_type");
                if (status.equals("rectify") && ftype == 1) {
                    op = "manage_approve";
                }
                if (status.equals("manage_approve") || (status.equals("rectify") && ftype == 0)) {
                    op = "review_approve";
                }
            }
        }
        if (op.equals("manage_approve")) { //专业部门审核
//            List<DeptRectifyViewEntity> ls = getDeptRectify(reqObj, jsonObject);
//            if (ls.size() > 0) {
            if (approve_result == 1) {
                userList.clear();
                List<RectifyHistoryEntity> historyList = rectifyService.getRectifyHistory(jsonObject.getString("problem_id"));
                for (RectifyHistoryEntity entity : historyList) {
                    if (entity.getOp_event().equals("rectify")) {
                        userList.add(entity.getOp_userid());
                        break;
                    }
                }
                wxSendMsgService.manageApproveTipInfo(userList, approve_result);
                //修改待办状态
                updateBacklog.setDbstatus("1");
                updateBacklog.setBmmc(strDutyDept);
//                    updateBacklog.setBmmc(ls.get(0).getDuty_dept());
            }
            if (approve_result == 0) {
                wxSendMsgService.manageApproveTipInfo(userList, approve_result);
                //修改待办状态
                updateBacklog.setDbstatus("6");
                updateBacklog.setBmmc(getSafeDeptPath(strDutyDept));
//                    updateBacklog.setBmmc(getSafeDeptPath(ConvertDeptToPath(ls.get(0).getBmmc())));
            }
//            }
        }
        if (op.equals("review_approve")) { //安监部门审核
//            List<DeptRectifyViewEntity> ls = getDeptRectify(reqObj, jsonObject);
//            if (ls.size() > 0) {
            if (approve_result == 1) {
                userList.clear();
                List<RectifyHistoryEntity> historyList = rectifyService.getRectifyHistory(jsonObject.getString("problem_id"));
                for (RectifyHistoryEntity entity : historyList) {
                    if (entity.getOp_event().equals("rectify")) {
                        userList.add(entity.getOp_userid());
                        break;
                    }
                }
            }
            wxSendMsgService.reviewApproveTipInfo(userList, approve_result);
            //修改待办状态
            updateBacklog.setDbstatus(approve_result == 1 ? "1" : "7");
            updateBacklog.setBmmc(strDutyDept);
//                updateBacklog.setBmmc(ls.get(0).getDuty_dept());
//            }
        }
        if (op.equals("commit")) { //落实整改
            if (check_type == 0) {
                wxSendMsgService.commitTipInfo(userList, check_type, 0);
                //修改待办状态
                updateBacklog.setDbstatus("4");
                updateBacklog.setBmmc("超高压输电公司/公司本部/安全监管部（应急指挥中心）");
            } else {
                List<DeptRectifyViewEntity> ls = getDeptRectify(reqObj, jsonObject);
                if (ls.size() > 0) {
                    wxSendMsgService.commitTipInfo(userList, check_type, ls.get(0).getFlow_type());
                    if (ls.get(0).getFlow_type() == 1) {
                        //修改待办状态
                        updateBacklog.setDbstatus("8");
                        updateBacklog.setBmmc(ls.get(0).getManage_dept());
                    } else {
                        //修改待办状态
                        updateBacklog.setDbstatus("4");
                        updateBacklog.setBmmc(getSafeDeptPath(ConvertDeptToPath(ls.get(0).getBmmc())));
                    }
                }
            }
        }
        if (op.equals("complete")) {//验收
            if (check_type == 0) {
                if (approve_result == 1) {
//                    List<CompanyRectifyViewEntity> ls = getCompanyRectify(reqObj, jsonObject);
//                    if (ls.size() > 0) {
                    userList.clear();
                    List<RectifyHistoryEntity> historyList = rectifyService.getRectifyHistory(jsonObject.getString("problem_id"));
                    for (RectifyHistoryEntity entity : historyList) {
                        if (entity.getOp_event().equals("commit")) {
                            userList.add(entity.getOp_userid());
                            break;
                        }
                    }
                    wxSendMsgService.completeTipInfo(userList, check_type);
                    //修改待办状态
                    updateBacklog.setDbstatus("3");
                    updateBacklog.setBmmc(strDutyDept);
//                        updateBacklog.setBmmc(ls.get(0).getDuty_dept());
//                    }
                } else {
                    updateBacklog.setDbstatus("-100");
                }
            } else {
                String status = jsonObject.getString("rectify_status");
                int ftype = jsonObject.getIntValue("flow_type");
                if (status.equals("commit") && ftype == 1) {
                    op = "manage_complete";
                }
                if (status.equals("manage_complete") || (status.equals("commit") && ftype == 0)) {
                    op = "review_complete";
                }
            }
        }
        if (op.equals("manage_complete")) {//专业部门验收
//            List<DeptRectifyViewEntity> ls = getDeptRectify(reqObj, jsonObject);
//            if (ls.size() > 0) {
            if (approve_result == 1) {
                userList.clear();
                List<RectifyHistoryEntity> historyList = rectifyService.getRectifyHistory(jsonObject.getString("problem_id"));
                for (RectifyHistoryEntity entity : historyList) {
                    if (entity.getOp_event().equals("commit")) {
                        userList.add(entity.getOp_userid());
                        break;
                    }
                }
                wxSendMsgService.manageCompleteTipInfo(userList, approve_result);
                //修改待办状态
                updateBacklog.setDbstatus("7");
                updateBacklog.setBmmc(strDutyDept);
//                    updateBacklog.setBmmc(ls.get(0).getDuty_dept());
            }
            if (approve_result == 0) {
                wxSendMsgService.manageCompleteTipInfo(userList, approve_result);
                //修改待办状态
                updateBacklog.setDbstatus("9");
                updateBacklog.setBmmc(getSafeDeptPath(strDutyDept));
//                    updateBacklog.setBmmc(getSafeDeptPath(ConvertDeptToPath(ls.get(0).getBmmc())));
            }
//            }
        }
        if (op.equals("review_complete")) {//安监部门最终验收
            if (approve_result == 1) {
//                List<DeptRectifyViewEntity> ls = getDeptRectify(reqObj, jsonObject);
//                if (ls.size() > 0) {
                userList.clear();
                List<RectifyHistoryEntity> historyList = rectifyService.getRectifyHistory(jsonObject.getString("problem_id"));
                for (RectifyHistoryEntity entity : historyList) {
                    if (entity.getOp_event().equals("commit")) {
                        userList.add(entity.getOp_userid());
                        break;
                    }
                }
                wxSendMsgService.completeTipInfo(userList, check_type);
                //修改待办状态
                updateBacklog.setDbstatus("7");
                updateBacklog.setBmmc(strDutyDept);
//                    updateBacklog.setBmmc(ls.get(0).getDuty_dept());
//                }
            } else {
                updateBacklog.setDbstatus("-100");
            }
        }
        if (!StringUtils.isEmpty(updateBacklog.getDbstatus())) {
            Map<String, Object> map = new HashMap<>();
            map.put("type", "1");
            map.put("problem_id", problem_id);
            List<BacklogEntity> dbList = daiBanService.selectdb(map);
            if (dbList.size() > 0) {
                if (updateBacklog.getDbstatus().equals("-100")) {
                    daiBanService.deleteBacklog(dbList.get(0).getId());
                } else {
                    updateBacklog.setId(dbList.get(0).getId());
                    updateBacklog.setNewTime("1");
                    daiBanService.updateBacklog(updateBacklog);
                }
            }
        }
    }

    private List<CompanyRectifyViewEntity> getCompanyRectify(JSONObject reqObj, JSONObject jsonObject) {
        Map<String, Object> condition = new HashMap<>();
        condition.put("problem_type", reqObj.getString("problem_type"));
        condition.put("problem_id", jsonObject.getString("problem_id"));
        List<CompanyRectifyViewEntity> ls = rectifyService.getCompanyRectifyListByConditionNoPage(condition);
        if (ls.size() == 0) {
            condition.put("problem_type", reqObj.getIntValue("problem_type") == 1 ? 0 : 1);
            ls = rectifyService.getCompanyRectifyListByConditionNoPage(condition);
        }
        return ls;
    }

    private List<DeptRectifyViewEntity> getDeptRectify(JSONObject reqObj, JSONObject jsonObject) {
        Map<String, Object> condition = new HashMap<>();
        condition.put("problem_type", reqObj.getString("problem_type"));
        condition.put("problem_id", jsonObject.getString("problem_id"));
        List<DeptRectifyViewEntity> ls = rectifyService.getDeptRectifyListByConditionNoPage(condition);
        if (ls.size() == 0) {
            condition.put("problem_type", reqObj.getIntValue("problem_type") == 1 ? 0 : 1);
            ls = rectifyService.getDeptRectifyListByConditionNoPage(condition);
        }
        return ls;
    }

    @GetMapping("/getRectifyHistory")
    public ResultVo getRectifyHistory(@RequestParam String id) {
        List<RectifyHistoryEntity> ls = rectifyService.getRectifyHistory(id);
        RectifyHistoryEntity historyEntity = new RectifyHistoryEntity();
        historyEntity.setOp_content("导入数据");
        historyEntity.setOp_event("Import");

        int problem_type = -1;
        boolean sscm = false;
        DwdggbmjdDataEntity dwEntity = dwdggbmjdDataService.selectDataId(id);
        if (dwEntity != null) {
            problem_type = 1;
            historyEntity.setOp_datetime(dwEntity.getDrtime() == null ? dwEntity.getCreateaTime() : dwEntity.getDrtime());
            if (StringUtils.isEmpty(dwEntity.getDrman())) {
                historyEntity.setOp_username(dwEntity.getPersonName());
            } else {
                UserEntity user = wxDepartmentService.getUserInfoByUserId(dwEntity.getDrman());
                historyEntity.setOp_username(user == null ? dwEntity.getDrman() : user.getUser_name());
            }
            if (dwEntity.getSscm().equals("公司层面")) {
                sscm = true;
                historyEntity.setNext_username("公司本部/安全监管部（应急指挥中心）");
            } else {
                historyEntity.setNext_username(getSafeDeptPath(ConvertDeptToPath(dwEntity.getBmmc())).replace("超高压输电公司/", ""));
            }
            ls.add(historyEntity);
        } else {
            GsdgdwjdDataEntity gsEntity = gsdgdwjdDataService.selectDataId(id);
            if (gsEntity != null) {
                problem_type = 0;
                historyEntity.setOp_datetime(gsEntity.getDrtime() == null ? gsEntity.getCreateaTime() : gsEntity.getDrtime());
                if (StringUtils.isEmpty(gsEntity.getDrman())) {
                    historyEntity.setOp_username(gsEntity.getPersonName());
                } else {
                    UserEntity user = wxDepartmentService.getUserInfoByUserId(gsEntity.getDrman());
                    historyEntity.setOp_username(user == null ? gsEntity.getDrman() : user.getUser_name());
                }
                if (gsEntity.getSscm().equals("公司层面")) {
                    sscm = true;
                    historyEntity.setNext_username("公司本部/安全监管部（应急指挥中心）");
                } else {
                    historyEntity.setNext_username(getSafeDeptPath(ConvertDeptToPath(gsEntity.getBmmc())).replace("超高压输电公司/", ""));
                }
                ls.add(historyEntity);
            }
        }
        if (ls.size() > 1 && problem_type != -1) {
            if (StringUtils.isEmpty(ls.get(0).getNext_username())) {
                Map<String, Object> condition = new HashMap<>();
                condition.put("problem_id", id);
                condition.put("problem_type", problem_type);
                if (sscm) {
                    List<CompanyRectifyViewEntity> list = rectifyService.getCompanyRectifyListByConditionNoPage(condition);
                    if (list.size() > 0) {
                        String status = list.get(0).getRectify_status();
                        if ("duty".equals(status) || "approve".equals(status)) {
                            ls.get(0).setNext_username(list.get(0).getDuty_dept().replace("超高压输电公司/", ""));
                        } else if ("unprocess".equals(status) || "commit".equals(status) || "rectify".equals(status)) {
                            ls.get(0).setNext_username("公司本部/安全监管部（应急指挥中心）");
                        }
                    }
                } else {
                    List<DeptRectifyViewEntity> list = rectifyService.getDeptRectifyListByConditionNoPage(condition);
                    if (list.size() > 0) {
                        String status = list.get(0).getRectify_status();
                        if ("duty".equals(status) || "approve".equals(status)) {
                            ls.get(0).setNext_username(list.get(0).getDuty_dept().replace("超高压输电公司/", ""));
                        } else if ("unprocess".equals(status) || "manage_approve".equals(status) || "manage_complete".equals(status)) {
                            ls.get(0).setNext_username(getSafeDeptPath(ConvertDeptToPath(list.get(0).getBmmc())).replace("超高压输电公司/", ""));
                        } else if ("rectify".equals(status) || "commit".equals(status)) {
                            if (list.get(0).getFlow_type() == 1) {
                                ls.get(0).setNext_username(list.get(0).getManage_dept().replace("超高压输电公司/", ""));
                            } else {
                                ls.get(0).setNext_username(getSafeDeptPath(ConvertDeptToPath(list.get(0).getBmmc())).replace("超高压输电公司/", ""));
                            }
                        }
                    }
                }
            }
        }
        return ResultVoUtil.success("success", ls);
    }

    private String bmmcToDeptFullPath(String bmmc) {
        return "超高压输电公司/" + bmmc.replaceAll("->", "/");
    }

    /**
     * 根据用户所在部门和审批类型，进行批量审批，同时批量记录日志
     */
    @PostMapping("/batchRectifyApprove")
    public ResultVo batchRectifyApprove(@RequestBody JSONObject req) {
        String user_dept = req.getString("user_dept");
        String userid = req.getString("user_id");
        String username = req.getString("user_name");
        String strProblemType = req.getString("problem_type");
        /**
         * 审批类型包括：review_approve 安监审批,manage_approve专业部门审批，review_complete安监验收,manage_complete专业管理部门验收
         */
        String approve_type = req.getString("approve_type");
        String approve_result = req.getString("approve_result");
        String rectify_type = req.getString("rectify_type");//company,dept

        Map<String, Object> updateCondition = new HashMap<String, Object>();
        updateCondition.put("rectify_type", rectify_type);
        updateCondition.put("op_userid", userid);
        updateCondition.put("op_username", username);
        updateCondition.put("complete_date", new Date());

        if (approve_type.equals("review_approve") && rectify_type.equals("company")) {
            if (approve_result.equals("0")) {
                updateCondition.put("rectify_status", "rectify");
                updateCondition.put("new_rectify_status", "approve");
                updateCondition.put("op_event", "approve");
                updateCondition.put("op_content", "整改措施审核通过");
                updateCondition.put("problem_type", Integer.parseInt(strProblemType));
            }
        }

        if (approve_type.equals("review_complete") && rectify_type.equals("company")) {
            if (approve_result.equals("0")) {
                updateCondition.put("rectify_status", "commit");
                updateCondition.put("new_rectify_status", "complete");
                updateCondition.put("complete_date", new Date());
                updateCondition.put("op_event", "approve");
                updateCondition.put("op_content", "整改验收通过");
                updateCondition.put("problem_type", Integer.parseInt(strProblemType));
            }
        }

        if (approve_type.equals("manage_approve") && rectify_type.equals("dept")) {
            if (approve_result.equals("0")) {
                updateCondition.put("rectify_status", "rectify");
                updateCondition.put("manage_dept", user_dept);
                updateCondition.put("new_rectify_status", "manage_approve");
                updateCondition.put("op_event", "manage_approve");
                updateCondition.put("op_content", "整改措施专业管理部门审核通过");
                updateCondition.put("problem_type", Integer.parseInt(strProblemType));
            }
        }

        if (approve_type.equals("manage_complete") && rectify_type.equals("dept")) {
            if (approve_result.equals("0")) {
                updateCondition.put("rectify_status", "commit");
                updateCondition.put("manage_dept", user_dept);
                updateCondition.put("new_rectify_status", "manage_complete");
                updateCondition.put("complete_date", new Date());
                updateCondition.put("op_event", "manage_complete");
                updateCondition.put("op_content", "整改专业管理部门验收通过");
                updateCondition.put("problem_type", Integer.parseInt(strProblemType));
            }
        }

        if (approve_type.equals("review_approve") && rectify_type.equals("dept")) {
            if (approve_result.equals("0")) {
                updateCondition.put("rectify_status", "rectify");
                updateCondition.put("review_dept", user_dept);
                updateCondition.put("new_rectify_status", "approve");
                updateCondition.put("op_event", "approve");
                updateCondition.put("op_content", "整改措施安监部门审核通过");
                updateCondition.put("problem_type", Integer.parseInt(strProblemType));
            }
        }

        if (approve_type.equals("review_complete") && rectify_type.equals("dept")) {
            if (approve_result.equals("0")) {
                updateCondition.put("rectify_status", "commit");
                updateCondition.put("review_dept", user_dept);
                updateCondition.put("new_rectify_status", "complete");
                updateCondition.put("op_event", "complete");
                updateCondition.put("op_content", "整改最终验收通过");
                updateCondition.put("problem_type", Integer.parseInt(strProblemType));
            }
        }

        rectifyService.batchRectifyApprove(updateCondition);

        return ResultVoUtil.success("success", null);
    }

    /**
     * 批量指定责任部门
     */
    @PostMapping("/batchRectifyDuty")
    public ResultVo batchRectifyDuty(@RequestBody JSONObject req) {
        String user_dept = req.getString("user_dept");
        String userid = req.getString("user_id");
        String username = req.getString("user_name");
        String strProblemType = req.getString("problem_type");
        String strDutyDept = "";//req.getString("duty_dept");
        /**
         * 审批类型包括：review_approve 安监审批,manage_approve专业部门审批，review_complete安监验收,manage_complete专业管理部门验收，duty-指定责任部门
         */
        String approve_type = req.getString("approve_type");
        String approve_result = req.getString("approve_result");
        String rectify_type = req.getString("rectify_type");//company,dept

        if (approve_type.equalsIgnoreCase("duty")) {
            //公司层面问题指定责任部门
            if (rectify_type.equalsIgnoreCase("company")) {
                Map<String, Object> lsCondition = new HashMap<String, Object>();
                lsCondition.put("rectify_status", "unprocess");
                lsCondition.put("problem_type", Integer.parseInt(strProblemType));

                List<CompanyRectifyViewEntity> ls = rectifyService.getCompanyRectifyListByConditionNoPage(lsCondition);

                if (ls != null && ls.size() > 0) {
                    for (int i = 0; i < ls.size(); i++) {
                        String problemid = ls.get(i).getProblem_id();
                        if (problemid == null || problemid.equals("")) {
                            Map<String, Object> insertCondition = new HashMap<String, Object>();
                            insertCondition.put("problem_id", ls.get(i).getId());
                            strDutyDept = bmmcToDeptFullPath(ls.get(i).getBmmc());
                            insertCondition.put("duty_dept", strDutyDept);
                            insertCondition.put("duty_date", new Date());
                            insertCondition.put("rectify_status", "duty");
                            insertCondition.put("problem_type", Integer.parseInt(strProblemType));

                            rectifyService.insertCompanyRectify(insertCondition);

                        } else {
                            Map<String, Object> updateCondition = new HashMap<String, Object>();
                            updateCondition.put("problem_id", ls.get(i).getProblem_id());
                            strDutyDept = bmmcToDeptFullPath(ls.get(i).getBmmc());
                            updateCondition.put("duty_dept", strDutyDept);
                            updateCondition.put("duty_date", new Date());
                            updateCondition.put("rectify_status", "duty");
                            rectifyService.updateCompanyRectify(updateCondition);

                        }

                        RectifyHistoryEntity historyEntity = new RectifyHistoryEntity();
                        historyEntity.setProblem_id(ls.get(i).getId());
                        historyEntity.setOp_content("指定责任部门：" + strDutyDept);
                        historyEntity.setOp_datetime(new Date());
                        historyEntity.setOp_event("duty");
                        historyEntity.setOp_userid(userid);
                        historyEntity.setOp_username(username);

                        rectifyService.insertRectifyHistory(historyEntity);
                    }
                }

            }

            //非公司层面问题指定责任部门
            if (rectify_type.equalsIgnoreCase("dept")) {
                Map<String, Object> lsCondition = new HashMap<String, Object>();
                lsCondition.put("rectify_status", "unprocess");
                lsCondition.put("problem_type", Integer.parseInt(strProblemType));

                //查询所以该单位的问题
                String strCompany = getUserCompany(user_dept);
                if (strCompany.endsWith("广州局")) {
                    lsCondition.put("ne_bmmc", "广州局->海口分局");
                }
                strCompany = strCompany.replaceAll("/", "->");
                lsCondition.put("bmmc", strCompany);

                List<DeptRectifyViewEntity> ls = rectifyService.getDeptRectifyListByConditionNoPage(lsCondition);

                if (ls != null && ls.size() > 0) {
                    for (int i = 0; i < ls.size(); i++) {
                        String problemid = ls.get(i).getProblem_id();
                        if (problemid == null || problemid.equals("")) {
                            Map<String, Object> insertCondition = new HashMap<String, Object>();
                            insertCondition.put("problem_id", ls.get(i).getId());
                            strDutyDept = bmmcToDeptFullPath(ls.get(i).getBmmc());
                            insertCondition.put("duty_dept", strDutyDept);
                            insertCondition.put("duty_date", new Date());
                            insertCondition.put("rectify_status", "duty");
                            insertCondition.put("problem_type", Integer.parseInt(strProblemType));

                            rectifyService.insertDeptRectify(insertCondition);

                        } else {
                            Map<String, Object> updateCondition = new HashMap<String, Object>();
                            updateCondition.put("problem_id", ls.get(i).getProblem_id());
                            strDutyDept = bmmcToDeptFullPath(ls.get(i).getBmmc());
                            updateCondition.put("duty_dept", strDutyDept);
                            updateCondition.put("duty_date", new Date());
                            updateCondition.put("rectify_status", "duty");
                            rectifyService.updateDeptRectify(updateCondition);

                        }

                        RectifyHistoryEntity historyEntity = new RectifyHistoryEntity();
                        historyEntity.setProblem_id(ls.get(i).getId());
                        historyEntity.setOp_content("指定责任部门：" + strDutyDept);
                        historyEntity.setOp_datetime(new Date());
                        historyEntity.setOp_event("duty");
                        historyEntity.setOp_userid(userid);
                        historyEntity.setOp_username(username);

                        rectifyService.insertRectifyHistory(historyEntity);
                    }
                }
            }

            return ResultVoUtil.success("success", null);
        }

        return ResultVoUtil.error("9999", "错误的批量操作");

    }
}
